package bamin.com.bamindaijia.Activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.refreshview.CustomerFooter;
import com.aiton.administrator.shane_library.shane.refreshview.XRefreshView;
import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.widget.SingleBtnDialog;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import bamin.com.bamindaijia.R;
import bamin.com.bamindaijia.adapter.MyAppointedOrderAdapter;
import bamin.com.bamindaijia.adapter.MyOrderAdapter;
import bamin.com.bamindaijia.constant.Constant;
import bamin.com.bamindaijia.model.AllOrder;
import bamin.com.bamindaijia.model.AppointedOrder;
import bamin.com.bamindaijia.model.Order;
import bamin.com.bamindaijia.model.OrderIng;
import bamin.com.bamindaijia.model.User;
import cz.msebera.android.httpclient.Header;


public class AllOrderActivity extends ZjbBaseActivity implements View.OnClickListener {
    private ListView mList_all_order;
    private MyOrderAdapter myOrderAdapter;
    private User mUser;
    private List<Order> mDatas = new ArrayList<>();
    private List<Order> mAppointedDatas = new ArrayList<>();

    private int userID;
    private boolean unfinished_order;
    private View listHead;
    private OrderIng mUnfinishOrderIng;
    private TextView mTv_time;
    private TextView mTv_state;
    private TextView mTv_start;
    private TextView mTv_end;
    private TextView mTv_price;
    private XRefreshView mCustom_view;
    private TextView mTv_order_null;
    private int orderPageCount = 1;//请求订单的页数
    private AllOrder allOrder;
    private ListView mList_search_order;
    private static final DateFormat FORMATTER = SimpleDateFormat.getDateInstance();
    private String replace;
    private MyAppointedOrderAdapter mMyAppointedOrderAdapter;
    private MaterialCalendarView mWidget;
    private Date time = Calendar.getInstance().getTime();
    private long SearchCalendarDialogShow;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_order);
        init();
    }

    @Override
    protected void initData() {
    }

    /**
     * 加载所有订单
     */
    private void loadAllOrder() {
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        //如果有待付款的订单，就下载订单信息
        if (unfinished_order) {
            String unfinishedUrl = Constant.Url.GET_ORDER_IS_ING;
            RequestParams params1 = new RequestParams();
            params1.put("customerId", "" + userID);//上传用户ID，从网络获取订单详情
            asyncHttpClient.post(unfinishedUrl, params1, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    String s = new String(responseBody);
                    try {
                        Log.e("onSuccess ", "未完成的订单（网络获取）:" + s);
                        mUnfinishOrderIng = GsonUtils.parseJSON(s, OrderIng.class);
                        Order datas = mUnfinishOrderIng.getDatas();
                        if (datas.getOrderTime() == null) {
                            listHead.setVisibility(View.GONE);
                        }
                        mTv_time.setText("下单时间：" + datas.getOrderTime());
                        mTv_state.setText("订单状态：待付款");
                        mTv_start.setText(datas.getStartLocation());
                        mTv_end.setText(datas.getEndLocation());
                        mTv_price.setVisibility(View.GONE);
                        loadOrder();
                    } catch (Exception e) {
                        Log.e("AllOrderActivity", "数据解析异常");
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Log.e("AllOrderActivity", "下载未完成订单失败");
                    mCustom_view.stopRefresh();
                }
            });
        } else {
            loadOrder();
        }
    }

    /**
     * 查看订单
     */
    private void loadOrder() {
        if (userID >= 0) {
            String url = Constant.Url.ALL_ORDER;
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            params.put("customerId", "" + userID);
            params.put("page", "" + orderPageCount);
            asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    String s = new String(responseBody);
                    Log.e("AllOrderActivity", "所有订单: --->>" + s);

                    try {
                        allOrder = GsonUtils.parseJSON(s, AllOrder.class);
                        List<Order> results = allOrder.getResults();
                        mDatas.addAll(results);
                        Log.e("AllOrderActivity", "mDatas: --->>" + mDatas.size());
                        if (mDatas.size() > 0) {
                            mList_all_order.setVisibility(View.VISIBLE);
                            mTv_order_null.setVisibility(View.GONE);
                        } else {
                            mTv_order_null.setVisibility(View.VISIBLE);
                            mList_all_order.setVisibility(View.GONE);
                        }
                        myOrderAdapter.notifyDataSetChanged();
                        mCustom_view.stopRefresh();
                        //每查询一次页数要+1
                        orderPageCount++;
                        cancelLoadingDialog();
                        Log.e("AllOrderActivity", "完成的订单: --->>" + orderPageCount);
                    } catch (Exception e) {
                        Log.e("AllOrderActivity", "下载订单异常");
                        Toast.makeText(AllOrderActivity.this, "下载订单异常", Toast.LENGTH_SHORT).show();
                        cancelLoadingDialog();

                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Log.e("AllOrderActivity", "下载订单失败");
                    mCustom_view.stopRefresh();
                    Toast.makeText(AllOrderActivity.this, "下载订单失败", Toast.LENGTH_SHORT).show();
                    cancelLoadingDialog();

                }
            });
        } else {
            mCustom_view.stopRefresh();
            mCustom_view.stopLoadMore();
            mTv_order_null.setVisibility(View.VISIBLE);
            cancelLoadingDialog();

        }
    }

    @Override
    protected void initViews() {

        myOrderAdapter = new MyOrderAdapter(this, mDatas);
        mList_all_order.setAdapter(myOrderAdapter);
        mMyAppointedOrderAdapter = new MyAppointedOrderAdapter(this, mAppointedDatas);
        mList_search_order.setAdapter(mMyAppointedOrderAdapter);
        initRefreshView();


    }



    /**
     * 刚开始进入自动下拉刷新
     */
    private void initRefreshView() {
        showLoadingDialog();
        mCustom_view.setPullLoadEnable(true);
        mCustom_view.setPinnedTime(1000);
        mCustom_view.setAutoLoadMore(true);
        mCustom_view.setMoveForHorizontal(true);
        mCustom_view.setAutoLoadMore(false);
        mCustom_view.setCustomFooterView(new CustomerFooter(this));
        mCustom_view.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                mDatas.clear();
                orderPageCount = 1;
//                hasUnFinishOrder();

                loadOrder();

                mTv_order_null.setVisibility(View.GONE);
            }

            @Override
            public void onLoadMore(boolean isSlience) {
                Log.e("onLoadMore ", "onLoadMore " + allOrder.isHasNext());
                mCustom_view.stopLoadMore();

                if (allOrder.isHasNext()) {

                    loadOrder();

                } else {
                    mCustom_view.stopLoadMore();
                    cancelLoadingDialog();
                    Toast.makeText(AllOrderActivity.this, "没有更多订单了", Toast.LENGTH_SHORT).show();
                }
            }
        });
        /**
         * 根据用户id查询所有订单号
         */
        mCustom_view.startRefresh();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUEST_RESULT_CODE.PINGJIA && resultCode == Constant.REQUEST_RESULT_CODE.PINGJIA) {
            mCustom_view.startRefresh();

        }
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageView_back).setOnClickListener(this);
        findViewById(R.id.img_search).setOnClickListener(this);
        mList_all_order.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                Log.e("AllOrderActivity", "position: --->>" + position);
//                if (unfinished_order && position == 0) {
//                    intent.setClass(AllOrderActivity.this, OrderIngActivity.class);
//                    startActivityTo(intent);
//                } else {
                //如果有未完成的订单，position-1
//                    position = unfinished_order ? position - 1 : position;
//                }
                Order resultsBean = mDatas.get(position);
                int appOrderStatus = resultsBean.getAppOrderStatus();
                //订单取消、完成、未评价，跳到订单详情
                if (appOrderStatus == Constant.ORDER_STATUS.CANCEL ||
                        appOrderStatus == Constant.ORDER_STATUS.ORDER_COMPLETE ||
                        appOrderStatus == Constant.ORDER_STATUS.NO_EVALUATION) {

                    intent.setClass(AllOrderActivity.this, OrderDetailActivity.class);
                    intent.putExtra(Constant.INTENT_KEY.TYPE, Constant.TYPE.ALLORDER);
                    intent.putExtra(Constant.INTENT_KEY.ORDER_DETAIL, resultsBean);
                    startActivityForResultTo(intent, Constant.REQUEST_RESULT_CODE.PINGJIA);
                } else {
                    intent.setClass(AllOrderActivity.this, OrderIngActivity.class);
                    startActivityTo(intent);
                }
//                    startActivityTo(intent);
            }
        });
        mList_search_order.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.setClass(AllOrderActivity.this, OrderDetailActivity.class);
                Order datasBean = mAppointedDatas.get(position);
                intent.putExtra(Constant.INTENT_KEY.TYPE, Constant.TYPE.APPOINTEDORDER);
                intent.putExtra(Constant.INTENT_KEY.ORDER_DETAIL, datasBean);
                startActivityForResultTo(intent, Constant.REQUEST_RESULT_CODE.PINGJIA);
//                startActivityTo(intent);
            }
        });
    }

    @Override
    protected void initSP() {


    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
        userID = intent.getIntExtra(Constant.INTENT_KEY.USER_ID, 0);
        Log.e("AllOrderActivity", "用户ID: --->>" + userID);
        Log.e("AllOrderActivity", "是否有未完成的订单: --->>" + unfinished_order);
    }

    @Override
    protected void findID() {
        mList_all_order = (ListView) findViewById(R.id.list_all_order);
        mTv_order_null = (TextView) findViewById(R.id.tv_order_null);
        listHead = getLayoutInflater().inflate(R.layout.item_order_info, null);
        mTv_time = (TextView) listHead.findViewById(R.id.textView_time);
        mTv_state = (TextView) listHead.findViewById(R.id.textView_OrderState);
        mTv_start = (TextView) listHead.findViewById(R.id.textView_start);
        mTv_end = (TextView) listHead.findViewById(R.id.textView_end);
        mTv_price = (TextView) listHead.findViewById(R.id.textView_price);
        mCustom_view = (XRefreshView) findViewById(R.id.custom_view);

        mList_search_order = (ListView) findViewById(R.id.list_search_order);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView_back:
                finishTo();
                break;
            case R.id.img_search://搜索订单
                if (System.currentTimeMillis() - SearchCalendarDialogShow <= 1000) {
                    return;
                }
                SearchCalendarDialogShow = System.currentTimeMillis();
                new SearchCalendarDialog(this).show();
                break;
        }
    }

    /**
     * 日历控件
     */
    public class SearchCalendarDialog extends Dialog implements OnDateSelectedListener {

        public SearchCalendarDialog(Context context) {
            super(context);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            View view = getLayoutInflater().inflate(R.layout.dialog_calendar, null);
            setContentView(view);

            TextView mTv_all_order = (TextView) view.findViewById(R.id.textView_all_order);
            mWidget = (MaterialCalendarView) view.findViewById(R.id.calendarView);

            mWidget.setOnDateChangedListener(this);
            mTv_all_order.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mList_search_order.setVisibility(View.GONE);
                    mCustom_view.setVisibility(View.VISIBLE);
                    initRefreshView();
                    dismiss();
                }
            });
            mWidget.setSelectedDate(time);
        }

        @Override
        public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
            String format = FORMATTER.format(date.getDate());
            time = date.getDate();
            mWidget.setSelectedDate(time);


            dismiss();
            replace = format.replace("年", "-").replace("月", "-").replace("日", "");
            Log.e("SearchCalendarDialog", "日历: --->>" + replace);
            Toast.makeText(AllOrderActivity.this, format, Toast.LENGTH_SHORT).show();


            loadSearchOrder();
        }
    }
// TODO: 2016/9/27

    /**
     * 加载搜索的订单
     */
    private void loadSearchOrder() {
        showLoadingDialog();
        String url = Constant.Url.APPOINTED_ORDER;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("customerId", userID);
        params.put("startDate", replace);
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                try {
                    Log.e("AllOrderActivity", "搜索的订单: --->>" + s);
                    AppointedOrder appointedOrder = GsonUtils.parseJSON(s, AppointedOrder.class);
                    if (appointedOrder.getStatus() == 0) {
                        List<Order> appointedOrderDatas = appointedOrder.getDatas();

                        mAppointedDatas.clear();

                        mAppointedDatas.addAll(appointedOrderDatas);
                        mMyAppointedOrderAdapter.notifyDataSetChanged();
                        mCustom_view.setVisibility(View.GONE);
                        mList_search_order.setVisibility(View.VISIBLE);
                        mTv_order_null.setVisibility(View.GONE);
                    } else {
                        mCustom_view.setVisibility(View.GONE);
                        mList_search_order.setVisibility(View.GONE);
                        mTv_order_null.setVisibility(View.VISIBLE);

                    }
                    cancelLoadingDialog();
                } catch (Exception e) {
                    showSingleDialog("文件解析错误", "确定");
                    mCustom_view.setVisibility(View.GONE);
                    mList_search_order.setVisibility(View.GONE);
                    mTv_order_null.setVisibility(View.VISIBLE);

                    cancelLoadingDialog();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                showSingleDialog("加载订单失败，服务器出错", "确定");
                mCustom_view.setVisibility(View.GONE);
                mList_search_order.setVisibility(View.GONE);
                mTv_order_null.setVisibility(View.VISIBLE);

                cancelLoadingDialog();
            }
        });

    }

    private void showSingleDialog(String title, String confirm) {
        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, title, confirm);
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                singleBtnDialog.dismiss();
            }
        });
        singleBtnDialog.show();
    }

}